<template>
  <div>
    <div id="root">
      <div class="todo-container">
        <div class="todo-wrap">
          <Header @add="addTodo" />
          <List :todos="todos" />
          <Footer :deleteAllDone="deleteAllDone"
                  :todos="todos"
                  :checkAllTodo="checkAllTodo"
                  v-show="todos.length" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from './components/Header'
import List from './components/List'
import Footer from './components/Footer'
export default {
  name: 'App',
  components: { Header, List, Footer },
  data() {
    return {
      todos: JSON.parse(localStorage.getItem('listAll')) || [],
    }
  },
  methods: {
    //数据在哪里，操作就在哪里
    //添加一个todo
    addTodo(todoObj) {
      //去todo中查询是否有同名的todo对象
      const result = this.todos.find((todo) => todo.title === todoObj.title)
      if (result) {
        //若有同名的
        alert('相同事件已存在，请核实后在添加！！')
      } else {
        //若没有同名的
        this.todos.unshift(todoObj)
        return true
      }
    },
    //删除一个todo
    deleteTodo(id) {
      //过滤掉不想要的todo项
      const fltTodos = this.todos.filter((todo) => todo.id !== id)
      //更新数据
      this.todos = fltTodos
    },
    //勾选or取消勾选一个的回调
    checkTodo(id, done) {
      console.log('@', id)
      this.todos.forEach((todo) => {
        if (todo.id === id) {
          todo.done = done
        }
      })
    },
    //清除所有已完成的
    deleteAllDone() {
      ///将所有未完成的筛选出来
      const fltTodos = this.todos.filter((todo) => !todo.done)
      //更新数据
      this.todos = fltTodos
    },
    //全选 or 取消全选todo
    checkAllTodo(done) {
      this.todos.forEach((todo) => {
        todo.done = done
      })
    },
  },
  watch: {
    todos: {
      deep: true,
      handler(value) {
        localStorage.setItem('listAll', JSON.stringify(value))
      },
    },
  },
  mounted() {
    //绑定全局事件总线事件
    this.$bus.$on('delete-todo', this.deleteTodo)
    this.$bus.$on('check-todo', this.checkTodo)
  },
  beforeDestroy() {
    //解绑全局事件总线事件
    this.$bus.$off('delete-todo')
    this, $bus.$off('check-todo')
  },
}
</script>

<style >
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2),
    0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>